package com.fishery.monitor.TimerJob;


import com.fishery.monitor.pojo.MeteorologicalData;
import com.fishery.monitor.pojo.MonitorBase;
import com.fishery.monitor.service.BaseService;
import com.fishery.monitor.service.MeteorologicalDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 到时放到服务器上面运行时，这里类的上面的两个注解的注释要去掉然后启动定时
 */

@Component
@EnableAsync
public class TimerUpdateData {

	@Autowired
	private GrabDataDemo grabDataDemo;

	@Autowired
	private MeteorologicalDataService meteorologicalDataService;

	@Autowired
	private BaseService baseService;


	//24小时  24*60*60*1000
	@Scheduled(fixedRate = 24 * 60 * 60 * 1000)
	public void addRecordedData() {

		try {
			System.out.println("正在执行任务..........");
			String addr = "60817411";
			//从前天的00点开始查
			String startTime = parseTime(System.currentTimeMillis() - 24 * 60 * 60 * 1000);
			//到今天的00点
			String endTime = parseTime(System.currentTimeMillis());
			String channelNumber = "";
			List<MeteorologicalData> ls = grabDataDemo.getHistoryData(addr, startTime, endTime, channelNumber);
			meteorologicalDataService.addList(ls);
			System.out.println("任务完成");
		} catch (ParseException e) {
			e.printStackTrace();

		}
	}

	@Scheduled(fixedRate = 24 * 60 * 60 * 1000)
	public void refresh() {

		try {
			System.out.println("正在刷新");
			List<MonitorBase> all = baseService.findAll();
			for (MonitorBase mb : all) {
				baseService.refresh(mb.getId());
			}

			System.out.println("刷新完成");
		} catch (Exception e) {
			e.printStackTrace();

		}
	}

	private String parseTime(long currentTimeMillis) {
		Date date = new Date(currentTimeMillis);
//        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//        String time = simpleDateFormat.format(date);
//        time=time.replace(" ","%20");
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String time = simpleDateFormat.format(date);
		return time;
	}


//    //半小时  30*60*1000
//    @Scheduled(fixedRate = 1000)
//    public void checkWarnData() {
//        //调用最新的数据，跟warn表的警告值进行比较
//        System.out.println("------ ------");
//    }
}
